package com.youlu.campus.service.rank.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.youlu.campus.activity.service.UserActivityTaskRankingService;
import com.youlu.campus.entity.UniversityInfo;
import com.youlu.campus.service.ranking.entity.UserActivityTaskRanking;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.UserParticipateActivityInfo;
import com.youlu.campus.entity.WechatH5UserPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RankingDataCheckService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserActivityTaskRankingService userActivityTaskRankingService;


    public void rankingCheck(List<String> activityIdList) {
        if (CollectionUtils.isEmpty(activityIdList)) {
            return;
        }
        log.info("开始清洗排名数据 ->{}", JSON.toJSONString(activityIdList));
        activityIdList.stream().forEach(activityId -> {
            doRankingByActivityId(activityId);
            log.info("结束清洗活动 ->{} 用户排名数据", activityId);
        });
        log.info("结束清洗排名数据 ->{}", JSON.toJSONString(activityIdList));
    }


    private void doRankingByActivityId(String activityId) {
        log.info("开始查询活动 ->{} 用户排名数据", activityId);
        Integer pageNo = 1;
        Integer pageSize = 1000;
        while (true) {
            //1、查询分页获取活动排名数据
            Query query = new Query();
            query.addCriteria(Criteria.where("activityId").is(activityId));
            Pageable pageRequest = PageRequest.of(pageNo - 1, pageSize);
            query.with(pageRequest);
            List<UserActivityTaskRanking> list = userActivityTaskRankingService.find(query);

            if (CollectionUtils.isEmpty(list)) {
                log.info("查询活动 ->{} 用户排名数据已结束", activityId);
                break;
            }
            log.info("查询活动 ->{} 用户排名数据 第 - > {} 页", activityId, pageNo);
            List<String> userIdList = list.stream().map(ranking -> ranking.getUserId()).collect(Collectors.toList());
            //2、查询分页批量获取活动用户报名排名
            query = new Query();
            query.addCriteria(Criteria.where("userId").in(userIdList));
            query.addCriteria(Criteria.where("activityId").is(activityId));
            List<UserParticipateActivityInfo> userList = this.mongoTemplate.find(query, UserParticipateActivityInfo.class);
            //用户匹配不上。则全部插入报名表
            if (CollectionUtils.isEmpty(userList)) {
                log.error("查询活动 ->{} 用户不在报名标中 排行榜用户数据 - >{} 报名表数据 - >{}", activityId, userIdList.size());
                doNotExistUser(activityId, userIdList);
            } else {
                //3、查询分页获取活动用户报名userId
                List<String> existUserIdList = userList.stream().map(user -> user.getUserId()).collect(Collectors.toList());
                if (userIdList.size() != existUserIdList.size()) {
                    log.info("活动 ->{} 用户排行榜数据 - >{} 报名表数据 - >{}", activityId, userIdList.size(), existUserIdList.size());
                    //不存在报名表中
                    List<String> notExistUserId = Lists.newArrayList();
                    userIdList.stream().forEach(userId -> {
                        //不存在报名表数据
                        long count = existUserIdList.stream().filter(existUserId -> !existUserId.equals(userId)).count();
                        if (count > 0) {
                            notExistUserId.add(userId);
                        }
                    });
                    log.info("活动 ->{} 用户排名数据不在当前活动报名表数据 - >{} ", activityId, notExistUserId.size());
                    doNotExistUser(activityId, notExistUserId);
                }
            }
            pageNo++;
        }


    }


    private void save(String activityId, String userId, UserParticipateActivityInfo userParticipateActivityInfo) {
        UserParticipateActivityInfo insertUserParticipateActivityInfo = new UserParticipateActivityInfo();
        insertUserParticipateActivityInfo.setQaScore(70D);
        insertUserParticipateActivityInfo.setJoined(Boolean.TRUE);
        insertUserParticipateActivityInfo.setName(userParticipateActivityInfo.getName());
        insertUserParticipateActivityInfo.setGrade(userParticipateActivityInfo.getGrade());
        insertUserParticipateActivityInfo.setMobile(userParticipateActivityInfo.getMobile());
        insertUserParticipateActivityInfo.setPassed(Boolean.TRUE);
        insertUserParticipateActivityInfo.setActivityId(activityId);
        insertUserParticipateActivityInfo.setUserId(userId);
        if (StringUtils.isNotBlank(userParticipateActivityInfo.getUniversityId())) {
            insertUserParticipateActivityInfo.setUniversityId(userParticipateActivityInfo.getUniversityId());
            UniversityInfo universityInfo = this.mongoTemplate.findById(userParticipateActivityInfo.getUniversityId(), UniversityInfo.class);
            if (Objects.nonNull(universityInfo)) {
                insertUserParticipateActivityInfo.setUniversityName(universityInfo.getName());
            }
        }
        insertUserParticipateActivityInfo.setRanking(Boolean.TRUE);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").in(userId));
        query.addCriteria(Criteria.where("joined").is(Boolean.TRUE));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        boolean exists = this.mongoTemplate.exists(query, UserParticipateActivityInfo.class);
        if (exists) {
            return;
        }
        this.mongoTemplate.save(insertUserParticipateActivityInfo);
    }


    private void doNotExistUser(String activityId, List<String> notExistUserList) {
        //3、查询分页获取活动用户报名userId
        //userId=?&joined=true,存在取手机号、姓名、大学，创建报名表
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").in(notExistUserList));
        query.addCriteria(Criteria.where("joined").is(Boolean.TRUE));
        List<UserParticipateActivityInfo> currentNotExistUserIdList = this.mongoTemplate.find(query, UserParticipateActivityInfo.class);
        //userId 可能对应多条
        Map<String, List<UserParticipateActivityInfo>> mapUserIdList = currentNotExistUserIdList.stream().collect(Collectors.groupingBy(UserParticipateActivityInfo::getUserId));
        mapUserIdList.forEach((userId, userItem) -> {
            //获取用户一条mobile不为空的
            //3.1、用户报名手机号不能为空
            Optional<UserParticipateActivityInfo> userMobileOptional = userItem.stream().filter(user -> StringUtils.isNotBlank(user.getMobile())).findFirst();
            if (userMobileOptional.isPresent()) {
                log.error("查询活动 ->{} 用户排名数据不在当前活动报名表数据 - >{} 新增报名信息【存在手机号】", activityId, userId);
                UserParticipateActivityInfo userParticipateActivityInfo = userMobileOptional.get();
                this.save(activityId, userId, userParticipateActivityInfo);
                return;
            }
            //3.2、用户报名表中手机号为空 查询用户账户信息表
            log.error("查询活动 ->{} 用户排名数据不在当前活动报名表数据 - >{} 未查询到手机号", activityId, userId);
            //userId 手机号 （mobile）报名表为空则 - 在userPo 和wechat-h5-user 中查找
            Query queryUser = new Query();
            queryUser.addCriteria(Criteria.where("mobile").ne(null));
            UserPO userAccount = this.mongoTemplate.findById(userId, UserPO.class);
            if (Objects.nonNull(userAccount)) {
                log.error("活动 ->{} add 用户账户信息 - >{}", activityId, userId);
                UserParticipateActivityInfo insertUserParticipateActivityInfo = new UserParticipateActivityInfo();
                insertUserParticipateActivityInfo.setName(userAccount.getName());
                insertUserParticipateActivityInfo.setGrade(userAccount.getGrade());
                insertUserParticipateActivityInfo.setMobile(userAccount.getMobile());
                insertUserParticipateActivityInfo.setUniversityId(userAccount.getUniversityId());
                insertUserParticipateActivityInfo.setUniversityName(userAccount.getUniversityName());
                this.save(activityId, userId, insertUserParticipateActivityInfo);
                return;
            }
            //3.3、用户报名表中手机号为空 查询用户基础信息表(wechatH5User)
            queryUser = new Query();
            queryUser.addCriteria(Criteria.where("accountInfoId").is(userId));
            queryUser.addCriteria(Criteria.where("mobile").ne(null));
            List<WechatH5UserPO> wechatH5UserList = this.mongoTemplate.find(queryUser, WechatH5UserPO.class);
            if (CollectionUtils.isNotEmpty(wechatH5UserList)) {
                log.error("活动 ->{}  add wechat用户信息 - >{}", activityId, userId);
                WechatH5UserPO wechatH5UserPO = wechatH5UserList.get(0);
                UserParticipateActivityInfo insertUserParticipateActivityInfo = new UserParticipateActivityInfo();
                insertUserParticipateActivityInfo.setName(wechatH5UserPO.getName());
                insertUserParticipateActivityInfo.setGrade(wechatH5UserPO.getGrade());
                insertUserParticipateActivityInfo.setMobile(wechatH5UserPO.getMobile());
                insertUserParticipateActivityInfo.setUniversityName(wechatH5UserPO.getUniversityName());
                insertUserParticipateActivityInfo.setUniversityId(wechatH5UserPO.getUniversityId());
                this.save(activityId, userId, insertUserParticipateActivityInfo);
            }
        });


    }
}
